﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using License;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;
using LeSoft.Application.Cache;

namespace LeSoft.Application.Web.Controllers
{

    [HandlerLogin(LoginMode.Ignore)]
    public class LoginController : MvcControllerBase
    {
        #region 视图功能
        /// <summary>
        /// 默认页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Default()
        {
            return View();
        }
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {

            return View();
        }
        public void GetCache()
        {
            new PStructCache().GetList();
            new RoomCache().GetList();
        }
        #endregion
        private AccountBLL accountBLL = new AccountBLL();
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult VerifyCode()
        {
            return File(new VerifyCode().GetVerifyCode(), @"image/Gif");
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult CheckLogin(string username, string password, string account, string verifycode, int autologin)
        {
            LogEntity logEntity = new LogEntity();
            logEntity.CategoryId = 1;
            logEntity.OperateTypeId = ((int)OperationType.Login).ToString();
            logEntity.OperateType = EnumAttribute.GetDescription(OperationType.Login);
            logEntity.OperateAccount = username;
            logEntity.OperateUserId = username;
            //logEntity.Module = Config.GetValue("SoftName");//string[] accountArr;
            string[] arr;
            try
            {

                #region 产品验证
                arr = Config.GetValue("ProductSecret") != null ? DESEncrypt.Decrypt(Config.GetValue("ProductSecret")).Split(',') : null;
                if (!arr.Contains("101")) return Error("产品已失效");

                #endregion
                #region 用户编号验证
                string ConstrName = string.Empty;
                if (Config.GetValue("CheckAccountCode") == "true")
                {
                    ConstrName = !account.IsEmpty() ? Config.GetValue(account) != null ? Config.GetValue(account) : "" : "";
                    if (ConstrName == "HZGDDB") SystemInfo.CurrentSystemName = "杭州国大运营管理系统V9";
                    else if (ConstrName == "DJZGDB") SystemInfo.CurrentSystemName = "东久中国营管理系统V9";
                    else if (ConstrName == "GZFDB") SystemInfo.CurrentSystemName = "浦东公租房运营管理系统V9";
                    else if (ConstrName == "BaseDb") SystemInfo.CurrentSystemName = "LeSoft物业经营管理系统V9";
                }
                else
                {
                    ConstrName = "BaseDb";
                    SystemInfo.CurrentSystemName = Config.GetValue("SystemName");
                }
                AccountEntity accountEntity = new AccountBLL().CheckLogin(ConstrName, username, password);
                if (accountEntity != null)
                {
                    AuthorizeBLL authorizeBLL = new AuthorizeBLL();
                    Operator operators = new Operator();
                    operators.CustomerCode = accountEntity.CustomerCode;
                    operators.Code = accountEntity.Code;
                    operators.UserId = accountEntity.AccountType < 5 && accountEntity.AccountType > 1 ? accountEntity.SourceId : accountEntity.Id;
                    operators.Account = accountEntity.Account;
                    operators.UserName = accountEntity.Name;
                    operators.Password = accountEntity.Password;
                    operators.SecretKey = accountEntity.Secretkey;
                    operators.ProductId = arr;
                    if (accountEntity.AccountType == 1)
                    {
                        operators.UserId = accountEntity.Id;
                        operators.ObjectId = accountEntity.Id;
                    }
                    else if (accountEntity.AccountType == 2)
                    {
                        //员工
                        WorkerEntity userEntity = new WorkerBLL().GetEntity(accountEntity.SourceId);
                        if (userEntity != null)
                        {
                            operators.CompanyId = userEntity.OrganizeId;
                            operators.DepartmentId = userEntity.DepartmentId;

                        }
                    }
                    else if (accountEntity.AccountType == 3)
                    {
                        //客户
                        CustomerInfoEntity userEntity = new CustomerInfoBLL().GetEntity(accountEntity.SourceId);
                        if (userEntity != null)
                        {
                            operators.CompanyId = userEntity.OrganizeId;
                            operators.ObjectId = accountEntity.Id;
                        }
                    }
                    else if (accountEntity.AccountType == 4)
                    {
                        //供应商
                        VendorEntity userEntity = new VendorBLL().GetEntity(accountEntity.SourceId);
                        if (userEntity != null)
                        {
                            operators.CompanyId = userEntity.OrganizeId;
                            operators.ObjectId = accountEntity.Id;
                        }
                    }
                    else
                    {//其他
                        operators.UserId = accountEntity.Id;
                        operators.ObjectId = accountEntity.Id;
                        operators.CompanyId = accountEntity.OrganizeId;
                    }
                    operators.ObjectId = new PermissionBLL().GetObjectStr(accountEntity.Id);//模块权限        
                    operators.IPAddress = Net.Ip;
                    operators.IPAddressName = IPLocation.GetLocation(Net.Ip);
                    operators.LogTime = DateTime.Now;
                    operators.Token = DESEncrypt.Encrypt(Guid.NewGuid().ToString());

                    //更新当前用户状态
                    accountEntity.LogOnCount = accountEntity.LogOnCount + 1;
                    accountEntity.UserOnLine = 1;
                    accountEntity.LastVisit = DateTime.Now;
                    accountEntity.IpAddress = Net.Ip;
                    accountBLL.SaveForm(accountEntity.Id, accountEntity);

                    //写入当前用户数据权限
                    //AuthorizeDataModel dataAuthorize = new AuthorizeDataModel();
                    //dataAuthorize.ReadAuthorize = authorizeBLL.GetDataAuthor(operators);
                    //dataAuthorize.ReadAuthorizeUserId = authorizeBLL.GetDataAuthorUserId(operators);
                    //dataAuthorize.WriteAuthorize = authorizeBLL.GetDataAuthor(operators, true);
                    //dataAuthorize.WriteAuthorizeUserId = authorizeBLL.GetDataAuthorUserId(operators, true);
                    //operators.DataAuthorize = dataAuthorize;
                    //判断是否系统管理员
                    // if (accountEntity.Account == "System")
                    //{
                    //    operators.IsSystem = true;
                    //}
                    //else
                    //{
                    //    operators.IsSystem = false;
                    //}
                    operators.IsSystem = true;
                    //写入当前用户数据权限 
                    //int type = StaticClass.AccountEntity.AuthorizeDataType == null ? -1 : (int)StaticClass.AccountEntity.AuthorizeDataType;
                    //StaticClass.AuthorizeManager = new AuthorizeManager(operators.UserId, type);
                    // operators.DataAuthorizeList = StaticClass.AuthorizeManager.GetCurrentModule();
                    OperatorProvider.Provider.AddCurrent(operators);
                    //写入日志
                    logEntity.Module = SystemInfo.CurrentSystemName;
                    logEntity.ExecuteResult = 1;
                    logEntity.ExecuteResultJson = "登录成功";
                    logEntity.WriteLog();
                }

                #endregion

                Thread th = new Thread(new ThreadStart(GetCache));
                th.Start();





                return Success("登录成功。");
            }
            catch (Exception ex)
            {
                WebHelper.DeleteCookie("LeSoft_autologin");                  //清除自动登录
                logEntity.ExecuteResult = -1;
                logEntity.ExecuteResultJson = ex.Message;
                logEntity.WriteLog();
                return Error(ex.Message);
            }
            // return Success("登录成功。");
        }

        /// <summary>
        /// 安全退出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult OutLogin()
        {
            LogEntity logEntity = new LogEntity();
            logEntity.CategoryId = 1;
            logEntity.OperateTypeId = ((int)OperationType.Exit).ToString();
            logEntity.OperateType = EnumAttribute.GetDescription(OperationType.Exit);
            logEntity.OperateAccount = OperatorProvider.Provider.Current().Account;
            logEntity.OperateUserId = OperatorProvider.Provider.Current().UserId;
            logEntity.ExecuteResult = 1;
            logEntity.ExecuteResultJson = "退出系统";
            logEntity.Module = Config.GetValue("SoftName");
            logEntity.WriteLog();

            //更新当前用户状态
            AccountEntity accountEntity = accountBLL.GetEntity(OperatorProvider.Provider.Current().UserId);
            accountEntity.UserOnLine = 0;
            accountEntity.LastVisit = DateTime.Now;
            accountEntity.IpAddress = Net.Ip;
            accountBLL.SaveForm(accountEntity.Id, accountEntity);

            Session.Abandon();                                          //清除当前会话
            Session.Clear();                                            //清除当前浏览器所有Session
            WebHelper.RemoveCookie("LeSoft_autologin");                  //清除自动登录
            return Content(new AjaxResult { type = ResultType.success, message = "退出系统" }.ToJson());
        }

        /// <summary>
        /// 登录限制
        /// </summary>
        /// <param name="account">账户</param>
        /// <param name="iPAddress">IP</param>
        /// <param name="iPAddressName">IP所在城市</param>
        //public void LoginLimit(string account, string iPAddress, string iPAddressName)
        //{
        //    if (account == "System")
        //    {
        //        return;
        //    }

        //    string platform = Net.Browser;
        //    accountBLL.LoginLimit(platform, account, iPAddress, iPAddressName);
        //}


    }
}
